package main

import (
	"image/color"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/driver/desktop"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
)

var _ fyne.Widget = (*Qizi)(nil)


type Qizi struct {
	widget.BaseWidget
	hovered  bool
	// 0 无棋子，1 红方，2 黑方
	Data1    int
	pos fyne.Position
	HoverColor,NormalColor color.Color
	Text     *canvas.Text
	Image    *canvas.Circle
	r        float32
	OnTapped func(*Qizi) `json:"-"`
}


func NewQizi(text string, fn func(*Qizi)) *Qizi {
	s := &Qizi{}
	s.HoverColor=blue
	s.NormalColor=color.Black
	s.Text = canvas.NewText(text, red)
	s.Image = canvas.NewCircle(green)
	s.Image.StrokeColor = color.Black
	s.Image.StrokeWidth = 2
	s.OnTapped = fn
	s.ExtendBaseWidget(s)
	return s
}
func (b *Qizi) Do(fn func(*Qizi)) *Qizi {
	if fn != nil {
		fn(b)
	}
	return b
}
func (me *Qizi) Tapped(*fyne.PointEvent) {
	if me.OnTapped != nil {
		me.OnTapped(me)
	}
}

func (b *Qizi) MouseIn(*desktop.MouseEvent) {
	b.hovered = true
	b.Refresh()
}

func (b *Qizi) MouseMoved(*desktop.MouseEvent) {
}

func (b *Qizi) MouseOut() {
	b.hovered = false
	b.Refresh()
}
func (me *Qizi) Cursor() desktop.Cursor {
	return desktop.PointerCursor
}


func (s *Qizi) CreateRenderer() fyne.WidgetRenderer {
	s.ExtendBaseWidget(s)
	return &qiziRenderer{
		d: s,
	}
}


func (s *Qizi) MinSize() fyne.Size {
	// return s.BaseWidget.MinSize()
	return fyne.NewSquareSize(20)
}

var _ fyne.WidgetRenderer = (*qiziRenderer)(nil)

type qiziRenderer struct {
	d *Qizi
}

func (r *qiziRenderer) Objects() []fyne.CanvasObject {
	return []fyne.CanvasObject{r.d.Image, r.d.Text}
}
func (r *qiziRenderer) Layout(size fyne.Size) {
	if size.Height > size.Width {
		r.d.r = size.Width
	} else {
		r.d.r = size.Height
	}
	r.d.Image.Resize(fyne.NewSquareSize(r.d.r - 5))

	ts := fyne.MeasureText(r.d.Text.Text, theme.TextSize(), fyne.TextStyle{})
	// r.d.Text.Resize(ts)
	// r.d.Image.Resize(ts.AddWidthHeight(10,10))
	r.d.Text.Move(fyne.NewSquareOffsetPos((r.d.r - ts.Width) * 0.4))
}
func (r *qiziRenderer) MinSize() fyne.Size {
	return fyne.MeasureText(r.d.Text.Text, theme.TextSize(), fyne.TextStyle{})
}

func (r *qiziRenderer) Refresh() {
	if r.d.hovered {
		r.d.Image.StrokeColor = r.d.HoverColor
		// r.d.Image.StrokeWidth = 2
	} else {
		r.d.Image.StrokeColor =r.d.NormalColor
		// r.d.Image.StrokeWidth = 0
	}
	r.d.Image.Refresh()
}

func (r *qiziRenderer) Destroy() {
}
